from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse

from user.forms import UserLoginFrom


def login(request):
    if request.method == 'GET':
        # get请求返回登录页面
        return render(request,'login.html')
    if request.method == 'POST':
        # 将请求参数丢给form表单做校验
        data = request.POST
        form = UserLoginFrom(data)
        # 检验结果，返回True表示检验成功
        if form.is_valid():
            user = auth.authenticate(username=form.cleaned_data.get('username'),password=form.cleaned_data.get('password'))
            if not user:
                # 没有user对象，表示验证密码不通过
                return render(request,'login.html')
            # 实现登录，request.user = 登录系统对象
            auth.login(request,user)
            return HttpResponseRedirect(reverse('user:index'))

        else:
            # 验证失败，返回错误信息给页面,errors是一个字典类型的，在页面中要errors.username,errors.password集中条件选择
            print('--------------------------')
            print(form.errors)
            return render(request,'login.html',{'errors':form.errors})

@login_required
# @login_required可以写在url中：url(r'^index/',login_required（views.index）,name='index'),
def index(request):
    if request.method == 'GET':
        return render(request,'index.html')


def user_list(request):
    if request.method == 'GET':
        return render(request,'user_list.html')